/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.gl.GlobalVariable;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.ui.manger.AjaxCallBackProxy;
import org.gl.utils.Tip;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.adapters.BusinessTabPagerAdapter;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.popuwindow.ButtonsPopuWindow;

public class CarerLostListFragment extends BaseFragment implements
		OnItemClickListener, OnHeaderRefreshListener, OnFooterRefreshListener,
		OnClickListener {
	OnListFragmentSelectedListener mCallback;
	DataSources ds;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	String[] keys = new String[] { "userName", "plate", "carName", "",
			"titleIconIndex" };
	ListView listView;
	JSONObject selectCarerInfo;
	protected JSONArray userListJosnAry = new JSONArray();
	private String businessType;
	private int titleIconIndex;

	public CarerLostListFragment(String businessType) {
		this.businessType = businessType;
	}

	public CarerLostListFragment(String businesstypeFirstmaintained,
			int position) {
		this(businesstypeFirstmaintained);
		this.titleIconIndex = position;
	}

	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);
	}

	public View view;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.order_carer_list, container, false);
		ds = new DataSources();
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		listView.setOnItemClickListener(this);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		initData(null);
		return view;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mButtonsPopuWindow = new ButtonsPopuWindow(context);
		mButtonsPopuWindow.setOnClick(CarerLostListFragment.this);
	}

	int page;
	PullToRefreshView mPullToRefreshView;
	SimpleAdapter adapter;

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page++;
				getData(page, businessType);
				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				getData(null, businessType);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}

	protected void initData(Integer _page) {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
		getData(null, businessType);

	}

	protected void getData(Integer _page, String businessType) {
		ds.getCarerMiss(_page,
				new AjaxCallBackProxy<String>(view.findViewById(R.id.loading)) {
					public void onLoading(long count, long current) {
					}

					@Override
					public void onFailure(Throwable t, int errorNo,
							String strMsg) {
						// TODO Auto-generated method stub
						super.onFailure(t, errorNo, strMsg);
					}

					public void onSuccess(String t) {
						lg.i(TAG, t);
						int code = 0;
						String mesage = "";
						try {
							JSONObject result = new JSONObject(t);
							;
							code = result.optInt(webkey.code);
							mesage = result.optString(webkey.reason);

							JSONArray newJsonArray = result
									.optJSONArray(webkey.result);
							contents.removeAll(contents);
							if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
								userListJosnAry = null;
								userListJosnAry = newJsonArray;
							} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
								for (int i = 0; i < newJsonArray.length(); i++) {
									userListJosnAry.put(newJsonArray.opt(i));
								}
							}
							if (userListJosnAry == null) {
								userListJosnAry = new JSONArray();
							}
							int count = userListJosnAry.length();
							if (userListJosnAry == null) {
								userListJosnAry = new JSONArray();
							} else {

							}
							JSONArray dstJSONArray;
							dstJSONArray = new JSONArray();
							for (int i = 0; i < count; i++) {
								JSONObject temp = userListJosnAry
										.optJSONObject(i).optJSONObject("user");
								temp.put("createTime",
										userListJosnAry.optJSONObject(i)
												.optString("createTime"));
								dstJSONArray.put(temp);
							}
							userListJosnAry = dstJSONArray;

							for (int i = 0; i < count; i++) {
								Map<String, Object> map = new HashMap<String, Object>();
								JSONObject temp = userListJosnAry
										.getJSONObject(i).optJSONObject("user");
								for (String key : keys) {
									Object o = temp.opt(key);
									if (o == null
											|| o.toString().equals("null")) {
										o = "";
									}
									if ("titleIconIndex".equals(key)) {
										o = BusinessTabPagerAdapter.icons[titleIconIndex];
									}
									if ("carName".equals(key)) {
										o = temp.optJSONObject("car")
												.optString(key);
									}
									map.put(key, o.toString());
								}
								contents.add(map);
							}
							if (adapter == null) {
								if (contents.size() > 0) {
									adapter = new SimpleAdapter(
											context,
											(List<Map<String, Object>>) contents,
											R.layout.list_item_business_carer,
											keys, new int[] { R.id.textView1,
													R.id.textView2,
													R.id.textView3,
													R.id.textView4,
													R.id.imageView1 });
									setListAdapter(adapter);
								}
							} else {
								adapter.notifyDataSetChanged();
							}
						} catch (Exception e) {
							e.printStackTrace();
						} finally {
							page--;
							if (code != 0) {
								loadFailed(mesage);
							} else {
								loadSuccessed();
								page++;
							}
						}

					}
				});
	}

	protected void setListAdapter(SimpleAdapter adapter) {
		listView.setAdapter(adapter);

	}

	@Override
	public void onStart() {
		super.onStart();
		// if (getFragmentManager().findFragmentById(R.id.article_fragment) !=
		// null) {
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		// }
	}

	ButtonsPopuWindow mButtonsPopuWindow;

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// Set the item as checked to be highlighted when in two-pane layout
		listView.setItemChecked(position, true);
		listView.setSelection(position);
		// try {
		// IntentExtraDataKeyValue.updateUserInfoToIntent(userListJosnAry
		// .getJSONObject(position).toString());
		// } catch (JSONException e) {
		// e.printStackTrace();
		// } catch (NullPointerException e) {
		// e.printStackTrace();
		// Toast.makeText(getActivity(), "null user&plate", Toast.LENGTH_SHORT)
		// .show();
		// }
		// // Notify the parent activity of selected item
		// // mCallback.onArticleSelected(position);
		// getActivity()
		// .startActivityForResult(
		// GlobalVariable.getGlobalInstance().intent
		// .setAction(ActivityActionName.CARER),
		// IntentExtraDataKey.ACTIVITY_QUESTCODE_UPDATECARERINFO);

		if (userListJosnAry != null) {
			selectCarerInfo = userListJosnAry.optJSONObject(position);
			try {
				selectCarerInfo.put("callType", businessType);
			} catch (JSONException e) {
				e.printStackTrace();
			}
			mButtonsPopuWindow.showWindow(arg1,selectCarerInfo);
		}
	}

	@Override
	public void receiveMessage(Object message) {
		super.receiveMessage(message);
		getData(null, businessType);
	}

	@Override
	public void onClick(View v) {
		if (selectCarerInfo == null) {
			lg.e(TAG, "onClick:selectCarerInfo is null");
			return;
		}
		switch (v.getId()) {
		case R.id.button1:
			Tip.show("1" + selectCarerInfo.toString());
			String tel = selectCarerInfo.optString("tel");
			if (!TextUtils.isEmpty(tel)) {
				Intent phoneIntent = new Intent("android.intent.action.CALL",
						Uri.parse("tel:" + tel));
				startActivity(phoneIntent);
			} else {
				Tip.show(getString(R.string.error_tel_requied));
			}
			break;
		case R.id.button2:
			IntentExtraDataKeyValue.updateUserInfoToIntent(selectCarerInfo
					.toString());
			context.startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.MessageBox));
			// FIXME 增加一个消息列表的activity
			break;
		case R.id.button3:
			IntentExtraDataKeyValue.updateUserInfoToIntent(selectCarerInfo
					.toString());
			context.startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.CARER));
			break;
		case R.id.button4:
			// TODO 增加一个地图位置的查看
			IntentExtraDataKeyValue.updateUserInfoToIntent(selectCarerInfo
					.toString());
			context.startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.MapLocation));
			break;
		case R.id.button5:
			// TODO 增加行车数据
			IntentExtraDataKeyValue.updateUserInfoToIntent(selectCarerInfo
					.toString());
			context.startActivity(GlobalVariable.getGlobalInstance().intent
					.setAction(ActivityActionName.CarRecordActivity));
			break;

		default:
			break;
		}

	}

	// /**
	// * 获取异常的白话文标题
	// *
	// * @param o
	// * @return
	// */
	// private String parshExcepiton(Object o,String value) {
	// char[] chas = o.toString().toCharArray();
	// String[] valueStringArray = value.split(",");
	// String exString = "";
	// for (int j = 0; j < chas.length; j++) {
	// if (j % 2 == 1) {
	// String s = "" + chas[j] + chas[j - 1];
	// if (!s.equals("00")) {
	// if ((chas[j - 1] + "").equals("1")) {
	// exString += exception[j / 2] + "过低:"+valueStringArray[j/2];
	// } else if ((chas[j] + "").equals("1")) {
	// exString += exception[j / 2] + "过高:"+valueStringArray[j/2];
	// } else {
	// exString += "未知"+valueStringArray[j/2];
	// }
	// }
	// }
	// }
	// return exString;
	// }
}